package com.sakuracard.stepdemo.model.base;

import com.sakuracard.stepdemo.annotation.RelData;
import lombok.Getter;
import lombok.Setter;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

public class TransferableBaseEntity {
  protected final transient Map<String, Object> extraData = new HashMap<>();

  /**
   * ID
   */
  @Getter
  @Setter
  private Integer id;

  /**
   * 名称
   */
  @Getter
  @Setter
  private String name;

  /**
   * 创建时间
   */
  @Getter
  @Setter
  private LocalDateTime createdTime;

  /**
   * 更新时间
   */
  @Getter
  @Setter
  private LocalDateTime updatedTime;

  /**
   * 创建人
   */
  @Getter
  @Setter
  private String createdUser;

  /**
   * 更新
   */
  @Getter
  @Setter
  private String updatedUser;

  public Map<String, Object> serializeEntity() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    Class cls = this.getClass();
    Field[] fields = cls.getDeclaredFields();
    StringBuilder sb = new StringBuilder();
    Map<String, Method> methodMap = new HashMap<>();
    Method[] methods = cls.getDeclaredMethods();
    for (Method method : methods) {
      methodMap.put(method.getName().toLowerCase(), method);
    }
    Map<String, Object> result = new HashMap<>();
    for (Field field : fields) {
      sb.setLength(0);
      RelData anno = field.getAnnotation(RelData.class);
      if (anno != null) {
        result.putIfAbsent(field.getName() + "_text", "未启用");
      }
      String getName = "get" + field.getName().toLowerCase();
      String isName = "is" + field.getName().toLowerCase();
      Method method = methodMap.get(getName);
      if (method == null) {
        method = methodMap.get(isName);
      }
      if (method != null) {
        result.put(field.getName(), method.invoke(this));
      }
    }
    return result;
  }
}
